﻿using System;
using System.Collections.Generic;
using System.Linq;
using Devbridge.IPolice.DataContracts;
using Devbridge.IPolice.DomainModel;
using Devbridge.IPolice.Repositories;
using Devbridge.IPolice.ServiceContracts;
using Devbridge.IPolice.Services.Dto;

using NHibernate.Linq;

namespace Devbridge.IPolice.Services
{
    public class CrimeService : ICrimeService
    {
        private readonly ICrimeRepository crimeRepository;

        public CrimeService()
        {
            crimeRepository = new CrimeRepository();
        }

        public CrimeSmall GetLastCrime()
        {
            var query = crimeRepository.AllQuery();

            return query
                    .Select(dbCrime => new CrimeSmall
                               {
                                   Id = dbCrime.Id,
                                   Description = dbCrime.Description,
                                   CrimeDate = dbCrime.Date
                               })
                    .FirstOrDefault();
        }

        public IList<CrimeSmall> GetSmallCrimes(out int count)
        {
            var query = crimeRepository.AllQuery().OrderByDescending(f => f.Date);

            var smallCrimesQuery = query.Select(
                dbCrime => new CrimeSmall
                               {
                                   Id = dbCrime.Id,
                                   Description = dbCrime.Description,
                                   CrimeDate = dbCrime.Date
                               });

            var currentDate = DateTime.Now;

            smallCrimesQuery = smallCrimesQuery
                .Where(smallCrime => smallCrime.CrimeDate >= currentDate.AddDays(-1) && smallCrime.CrimeDate <= currentDate);
           
            count = smallCrimesQuery.Count();

            return smallCrimesQuery.ToList();
        }

        public IList<Crime> GetCrimes(DateTime from, DateTime to)
        {
            var query = crimeRepository.AllQuery();

            query = query.Where(crime => crime.Date >= from.Date && crime.Date <= to.Date.AddDays(1));       

            var crimes = query
                            .Fetch(crime => crime.Offender)
                            .Fetch(crime => crime.AssignedPoliceOfficer)
                            .ToList();

            return crimes;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            crimeRepository.Dispose();
        }
    }
}